package pt.mauromad.guias.controller;

import static java.lang.String.format;
import static pt.mauromad.guias.utils.transformation.Transformations.Product2Bean;
import static pt.mauromad.guias.utils.transformation.Transformations.Product2Dao;

import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import pt.mauromad.guias.bean.ProductBean;
import pt.mauromad.guias.dao.ProductDao;
import pt.mauromad.guias.refdata.mesure.Measure;
import pt.mauromad.guias.utils.form.Action;

@Controller
@RequestMapping("/product")
public class ProductController extends BaseController {
	@RequestMapping(value = "/all")
	public String all(Model model) {
		model.addAttribute("products", productService.byAccount(getAccount()));
		return "list/all-products";
	}

	@RequestMapping(value = "/all", params = "action=json")
	@ResponseBody
	public List<ProductBean> allJson() {
		return Product2Bean.get(productService.byAccount(getAccount()));
	}

	@RequestMapping(value = "/new", method = RequestMethod.GET)
	public String create(Model model) {
		model.addAttribute("editable", true);
		model.addAttribute("measureList", Measure.values());
		add(model, Action.createPost("save"));
		return "product-form";
	}

	@RequestMapping(value = "/new", method = RequestMethod.POST)
	public String createProduct(Model model, @Validated ProductBean bean) {
		ProductDao dao = Product2Dao.get(bean);
		dao.setAccount(getAccount());
		productService.save(dao);
		return format("redirect:/product/%s", dao.getId());
	}

	@RequestMapping(value = "/{product:[0-9]+}", method = RequestMethod.GET)
	public String show(Model model, @PathVariable ProductDao product) {
		model.addAttribute("product", product);
		add(model, Action.createPost("manage"));
		return "product-form";
	}

	@RequestMapping(value = "/{product:[0-9]+}", method = RequestMethod.POST, params = "action=manage")
	public String manage(Model model, @PathVariable ProductDao product) {
		model.addAttribute("product", product);
		model.addAttribute("measureList", Measure.values());
		model.addAttribute("editable", true);
		add(model, Action.createPost("manage.save"));
		return "product-form";
	}

	@RequestMapping(value = "/{product:[0-9]+}", method = RequestMethod.POST, params = "action=manage.save")
	public String manageSave(Model model, @Validated ProductBean bean, @PathVariable Long product) {
		bean.setId(product);
		productService.save(Product2Dao.get(bean));
		return format("redirect:/product/%s", product);
	}
}
